package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.constant.MessageConst;
import com.itheima.constant.RedisMessageConst;
import com.itheima.entity.Result;
import com.itheima.pojo.Member;
import com.itheima.service.MemberService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.JedisPool;

import java.util.Date;
import java.util.Map;

@RequestMapping("/login")
@RestController
public class LoginController {

    @Autowired
    JedisPool jedisPool;

    @Reference
    MemberService memberService;

    /*
     * 1. 获取客户端手机号及验证码
     * 2. 根据手机号获取redis验证码
     * 3. 判断用户验证码与redis验证码是否匹配
     *    1. 如果匹配失败，返回验证码错误
     *    2.如果成功，根据手机号获取会员信息
     *        1. 如果有会员，登录成功
     *        2. 如果不是会员，封装Member对象，调用Service保存
     * */
    @RequestMapping("/check")
    public Result check(@RequestBody Map<String, Object> map) {
        try {
            String validateCode = String.valueOf(map.get("validateCode"));
            String telephone = String.valueOf(map.get("telephone"));
            String validateCodeInRedis = jedisPool.getResource().get(RedisMessageConst.SENDTYPE_LOGIN + "-" + telephone);

            if (!(validateCodeInRedis != null && validateCodeInRedis.equals(validateCode))) {
                return new Result(false, MessageConst.VALIDATECODE_ERROR);
            }

            if (validateCodeInRedis == null || validateCodeInRedis.length() == 0) {
                return new Result(false, MessageConst.VALIDATECODE_INVALID);
            }

            //判断是否是会员
            Member member = memberService.findByTelephone(telephone);
            //不是会员,需要注册为会员
            if (member == null){
                member = new Member();
                member.setPhoneNumber(telephone);
                member.setRegTime(new Date());
                memberService.add(member);
            }

            return new Result(true, MessageConst.LOGIN_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConst.LOGIN_FAIL);
        }
    }
}
